<template>
  <div class="login-container">
    <el-form
      :model="loginForm"
      status-icon
      :rules="rules"
      ref="loginForm"
      label-width="100px"
      class="login-loginForm"
    >
      <h1 class="title" v-text="title"></h1>
      <!-- 来回切换 -->
      <i
        @click="(isErweiLogin = !isErweiLogin), (isSmsLogin = false)"
        :class="['jiaobiao', 'iconfont', jiaobiao]"
      ></i>

      <div class="common-login" v-if="!isErweiLogin && !isSmsLogin">
        <el-form-item label="用户名" prop="username">
          <el-input
            type="text"
            v-model="loginForm.username"
            autocomplete="off"
          ></el-input>
        </el-form-item>
        <el-form-item label="密码" prop="password">
          <el-input
            type="password"
            v-model="loginForm.password"
            autocomplete="off"
          ></el-input>
        </el-form-item>

        <el-form-item label="验证码" prop="captcha">
          <el-input
            maxlength="5"
            v-model="loginForm.captcha"
            class="captcha"
            ref="captcha"
            @keydown.native.enter="submitForm('loginForm')"
          ></el-input>
          <!--  native触发原生dom -->
          <span @click="updateCaptcha" class="captcha-svg" v-loading="loading">
            <i v-html="captchaSvg"></i>
          </span>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="submitForm('loginForm')"
            >提交</el-button
          >
        </el-form-item>

        <el-form-item>
          <div class="sms">
            <svg class="icon" aria-hidden="true">
              <use xlink:href="#icon-iphone"></use>
            </svg>
            <a
              href="javascript:;"
              @click="isSmsLogin = true"
              style="color: #fff; font-size: 16px"
              >切换短信登入</a
            >
          </div>
        </el-form-item>
      </div>
      <!-- 二维码验证 -->
      <div class="erwei" v-else-if="isErweiLogin && !isSmsLogin">
        <div class="img" v-loading="qrLoading">
          <img :src="imgBase64Url" width="200px" alt="" />
          <i
            class="mask"
            :style="qrStyle"
            @click="getQrcode"
            v-show="showQrMask"
          >
          </i>
        </div>
        <p v-text="qrtip"></p>
      </div>
      <!-- 短信验证 -->
      <div class="smsContainer" v-else>
        <el-form-item label="手机号">
          <el-input
            maxlength="11"
            v-model="phoneNumber"
            class="captcha phone"
          ></el-input>
          <span
            @click="sendSmsCode"
            class="captcha-svg"
            v-text="smsRetryMsg"
            style="color: #888; line-height: 45px; text-decoration: underline"
          >
          </span>
        </el-form-item>
        <el-form-item label="验证码">
          <el-input v-model="smsCode" maxlength="5"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="smsSubmit">提交</el-button>
        </el-form-item>
      </div>
    </el-form>
  </div>
</template>
<script>
import * as api from "@/api/users";

import socketIo from "socket.io-client";

import qr from "qrcode";

import scancodeSuccessPic from "../../assets/img/scancode.png";
import invalidPic from "../../assets/img/invalidQr.png";
var validateCaptcha = (rule, value, callback) => {
  if (value.length !== 5) {
    callback("验证码必须是5位");
  } else {
    callback();
  }
};
var validateUsername = (rule, value, callback) => {
  // console.log(value);
  var reg = /^\w{3,12}$/;
  if (reg.test(value)) {
    callback();
  } else {
    callback("用户名可以是字母数字下划线,3-12位");
  }
};
var validatePassword = (rule, value, callback) => {
  if (value.length < 3) {
    callback(new Error("密码长度不能小于3位"));
  } else {
    callback();
  }
};
export default {
  name: "login",

  data() {
    return {
      showQrMask: false,
      smsDisabled: false,
      smsRetryMsg: "点击发送验证码",
      smsCode: "",
      title: "千锋管理系统",
      captchaSvg: "",
      codeLoading: true,
      qrtip: "请使用手机微信扫码登入",
      isSmsLogin: false,
      isErweiLogin: false,
      phoneNumber: "",
      isScanCodeSuccess: false,
      qrLoading: true,

      loginForm: {
        username: "",
        password: "",
        captcha: "",
      },
      rules: {
        username: [{ validator: validateUsername, trigger: "blur" }],
        password: [{ validator: validatePassword, trigger: "blur" }],
        captcha: [{ validator: validateCaptcha, trigger: "blur" }],
      },
      imgBase64Url: "",
      qrStyle: {
        backgroundImage: `url(${invalidPic})`,
      },
    };
  },

  computed: {
    jiaobiao() {
      return this.isErweiLogin
        ? "icon-diannaojiaobiao"
        : "icon-erweimajiaobiao";
    },
  },

  created() {
    this.updateCaptcha();
  },

  methods: {
    async smsSubmit() {
      let smsLoginRes = await api.smsLogin(this.smsCode);
      console.log(smsLoginRes);

      let {
        userInfo,
        state,
        permission: { buttons },
        token,
      } = smsLoginRes.data;
      if (state) {
        localStorage.setItem("qf-userInfo", JSON.stringify(userInfo));
        localStorage.setItem("qf-permissionBtn", JSON.stringify(buttons));
        localStorage.setItem("qf-token", token);
      }
      this.$router.push("/");
    },
    // 发送短信
    async sendSmsCode() {
      console.log(this.phoneNumber);
      if (this.smsDisabled) {
        this.$message.error("1分钟内只能发送一次");
      }
      let smsResult = await api.getSmsCode(this.phoneNumber);

      let { state } = smsResult.data;
      if (state) {
        this.$smsDisabled = true;
        this.$message.success("短信发送成功");
        // console.log(smsResult)
        this.smsSecond = 60;
        this.smsInterval = setInterval(() => {
          this.smsSecond--;
          if (this.smsSecond == 0) {
            clearInterval(this.smsInterval);
            this.smsRetryMsg = "点击发送验证";
            this.$smsDisabled = false;
            return;
          }
          this.smsRetryMsg = `${this.smsSecond}秒后重新发送`;
        }, 1000);
      }
      console.log(smsResult);
    },

    async getQrcode(sid) {
      this.imgBase64Url=""
      this.showQrMask = false;
      this.qrLoading = true;
      // 从本地存储里取sid,如果没有就是从下面获取sid
      sid = localStorage.getItem("qf-sid") ?? sid;
      console.log(sid);
      let qrResult = await api.getQrcode(sid);

      console.log(qrResult);

      let { scanCodeUrl, state: getQrState } = qrResult.data;

      console.log(scanCodeUrl);
      if (getQrState) {
        qr.toDataURL(scanCodeUrl, (err, imgBase64Url) => {
          if (err) {
            this.$messageBox.error(err);
            return;
          }
          // console.log(imgBase64Url)
          this.imgBase64Url = imgBase64Url;

          this.qrLoading = false;
        });
      }
    },
    updateCaptcha() {
      this.loading = true;
      api.getCaptcha().then((res) => {
        let { img } = res.data; //解构验证码
        this.captchaSvg = img;
        this.loading = false;
      });
    },
    // 登录逻辑：进行本地的表单校验
    // 通过v-model获取输入的username，password
    // 校验验证码
    // 发起请求，请求登入接口，传入用户名和密码
    // 跳转到主页，显示主页
    submitForm(formName) {
      this.$refs[formName].validate((valid) => {
        if (valid) {
          // 打开加载动画
          const loading = this.$loading({
            lock: true,
            text: "正在登入",
            spinner: "el-icon-loading",
            background: "rgba(0, 0, 0, 0.7)",
          });
          setTimeout(() => {
            loading.close();
          }, 2000);

          let { username, password, captcha } = this.loginForm;
          api.verifyCaptcha(captcha).then(async (res) => {
            let { state } = res.data;
            if (state) {
              let loginRes = await api.login(username, password);
              console.log(loginRes);
              let { state: loginState, msg, token, userInfo } = loginRes.data;
              if (loginState) {
                // 登入成功，关闭动画
                loading.close();
                localStorage.setItem("qf-token", token);
                this.$router.push("/");
                this.$message({
                  message: msg,
                  type: "success",
                  duration: 1000,
                });
              } else {
                loading.close();
              }
            }
          });
        }
      });
    },
  },
  watch: {
    // 监听切换短信验证
    isSmsLogin(val) {
      if (!val) {
        if (this.smsInterval) {
          clearInterval(this.smsInterval);
        }
        this.smsRetryMsg = "点击发送验证码";
      }
    },

    isErweiLogin(isErwei) {
      if (isErwei) {
        // 建立socket链接
        let io = socketIo("wss://chst.vip");
        this.qrLoading = true;
        // 遮罩关闭
        this.showQrMask = false;

        // 扫码成功
        io.on("scancodeSuccess", async (data) => {
          this.showQrMask = true;
          this.qrStyle.backgroundImage = `url(${scancodeSuccessPic})`;
          console.log(data);
          let { state: scanCodeState, wechatCode } = data;

          // console.log(scancodeState)

          if (scanCodeState) {
            let scanCodeRes = await api.wechatLogin(wechatCode);

            console.log(scanCodeRes);

            let {
              state,
              userInfo,
              permission: { buttons },
              token,
            } = scanCodeRes.data;

            if (state) {
              localStorage.setItem("qf-userInfo", JSON.stringify(userInfo));
              localStorage.setItem("qf-permissionBtn", JSON.stringify(buttons));
              localStorage.setItem("qf-token", token);

              this.$router.push({ path: "/" });

              this.showQrMask = false;
            }
          }
        });
        // 失效的二维码
        io.on("invalidCode", (data) => {
          // console.log(data);
          let { state } = data;
          if (!state) {
            this.showQrMask = true;
            this.qrtip = "二维码失效，请点击重新获取二维码";
          }
        });
        //  连接成功
        io.on("connectSuccess", async (data) => {
          // console.log(data);
          let { sid } = data;

          localStorage.setItem("qf-sid", sid);

          this.getQrcode(sid);
        });
      }
    },
  },
};
</script>
<style scoped>
/* html body {
  width: 100%;
  height: 100%;
  overflow: hidden;
} */
.login-container {
  text-align: center;
  color: #fff;
  /* background: hotpink; */
}

.login-container .el-form {
  position: fixed;
  right: 10%;
  top: 25%;
  border-radius: 5px;
  width: 400px;
  background-color: skyblue;
  padding: 100px 0 50px 0;
}

.el-form /deep/ .el-input__inner {
  width: 250px;
}

.el-input__inner {
  width: 250px;
}
.el-form /deep/ .captcha {
  width: 100px;
  vertical-align: top;

}
.el-input__inner {
  width: 100%;
  height: 45px;
  border-radius: 5px 0 0 5px;
  border: 0;
  font-size: 18px;
}
.el-button {
  width: 250px;
}

.el-form /deep/ .captcha {
  width: 100px;
  vertical-align: top;
}
.el-form .el-input__inner {
  width: 100%;
  height: 45px;
  border-radius: 5px 0 0 5px;
  border: 0;
  font-size: 18px;
}

.captcha-svg {
  background: #fff;
  display: inline-block;
  height: 45px;
  width: 150px;
  text-align: center;
  cursor: pointer;
  border: 0;
  border-radius: 0px 5px 5px 0;
  position: relative;
  z-index: 99;
  /* background:yellow; */
}
.jiaobiao {
  font-size: 60px;
  color: #fff;
  position: absolute;
  right: -1px;
  top: -1px;
  cursor: pointer;
  opacity: 0.7;
}
.mask {
  width: 100%;
  height: 100%;
  opacity: 0.8;
  background-color: #fff;
  position: absolute;
  left: 0;
  background-size: 50%;
  background-repeat: no-repeat;
  background-position: center;
  cursor: pointer;
}
.erwei .img {
  display: inline-block;
  position: relative;
  width: 200px;
  height: 200px;
}

img {
  position: absolute;
  left: 0;
}
</style>
  